<template>
    <div class="rate-container">
        <div class="content">
            <template v-for="question in MyCommentContent.questionList" :key="question.id">
                <div class="rate-content rate-box" v-if="question.questionType === 7">
                    <div class="rate-item" v-for="(item, index) in question.content.row" :key="item.index">
                        <span class="rate-label">{{item.title}}</span>
                        <van-rate
                        v-model="item.col[0].answer.answer"
                        :size="22"
                        icon="https://d1-dev.3ren.cn/static/front-res/xc-h5/img/star.png"
                        void-icon="https://d1-dev.3ren.cn/static/front-res/xc-h5/img/star-o.png"
                        :readonly="!!MyCommentContent.assessUser"/>
                        <span class="rate-value" v-if="item.col[0].answer.answer">{{item.col[0].answer.answer}}分</span>
                    </div>
                </div>
                <div class="rate-content rate-desc"  v-if="question.questionType === 8">
                    <van-cell-group v-if="!MyCommentContent.assessUser" inset>
                        <van-field
                            id="scroll_text"
                            v-model="content"
                            autosize
                            label=""
                            type="textarea"
                            placeholder="有什么感悟要分享吗"
                            maxlength="500"
                        />
                    </van-cell-group><!-- @update:model-value="changeContent"-->
                    <div class="rate-desc-readonly" v-else v-html="content"></div>
                </div>
            </template>
            
        </div>
        <footer v-if="!MyCommentContent.assessUser">
            <van-button type="primary" @click="checkValidAssess">发布</van-button>
        </footer>
        <van-popup v-model:show="show" round position="bottom" safe-area-inset-bottom>
            <div class="confirm-header">
                <div class="confrim-title">
                    确认发布评分吗？
                </div>
                <div class="confirm-desc">发布后不可修改</div>
            </div>
            <div class="confirm-ok" @click="submit">确认发布</div>
            <div class="confirm-cancel" @click="cancel">取消</div>
        </van-popup>
        <van-popup v-model:show="showExit" round position="bottom" safe-area-inset-bottom>
            <div class="confirm-header">
                <div class="confrim-title">
                    确认退出吗？
                </div>
                <div class="confirm-desc">退出将不保存修改</div>
            </div>
            <div class="confirm-ok" @click="exit">确认退出</div>
            <div class="confirm-cancel" @click="cancelExit">取消</div>
        </van-popup>
    </div>
</template>

<script setup>
import { preview } from '@yanxiu/player';
import { onMounted, reactive, ref, computed, nextTick } from 'vue';
import { useRoute, onBeforeRouteLeave } from 'vue-router';
import { useStore } from 'vuex';
import { Rate, Field, CellGroup, Popup } from 'vant';
import { deepCopy } from '@/lib/tools';
import { handleErrorPage } from '@/lib/tools.js';
import {isApp} from '@/lib/judge-env.js';

const route = useRoute();
const store = useStore();

const loading = ref(false);
const show = ref(false)
// 慕课详情数据
const detailData = ref({});
const assessInfo = ref({});
// 我的评论内容
const MyCommentContent = ref({});
let initInfo
let isNext = true;
const showExit = ref(false)

let answerObj = reactive({});
let answerObj1 = reactive({});

const answerArrToValid = ref([]);

const content = ref('');
let maxLength = ref(500);
let minLength = ref(0);

const currentUser = computed(() => {
    return store.state?.currentUser || {};
});

// 获取评论模板信息
function getCommentTemplate () {
    // 慕课id不存在、慕课问卷id不存在或者是管理员不能评价
    if (!route.params.moocId || !route.params.assessId) {
        return false
    }
    assessInfo.value = {
        assessId: route.params.assessId,
        subBizId: route.params.moocId || '',
        subBizType: 'mooc',
        // queryInvalid: true // 查询包括删除的
    }
    G_transmit('queryAssessAnswer', {
        queries: assessInfo.value
    }).then((res) => {
        MyCommentContent.value = res.data || {};
        if(MyCommentContent.value.assessUser) {
            store.dispatch('jsBridge/disposeBridge', {
                method: 'setNativeTitle',
                options: {
                    title: '我的评分',
                    showBack: true
                }
            });
        }
        MyCommentContent.value.questionList.forEach((question)=> {
            if(question.questionType === 7) {
                (question.userAnswerList || []).forEach(item => {
                    answerObj[item.questionIndex] = item;
                });
                let col = question.content && question.content.col || [];
                let row = question.content && question.content.row || [];
                row.map(r => {
                    let temp = [...col];
                    temp = temp.map((item, index) => {
                        return deepCopy(item);
                    });
                    r.col = (temp).map(c => {
                        let reg = new RegExp(`\^${r.index}-${c.index}-*`);
                        let reg1 = new RegExp(`\^${r.index}-${c.index}`);
                        c.answer = { answer: 0 };
                        for(let key in answerObj) {
                            if(reg.test(key) || reg1.test(key)) {
                                if(answerObj[key] && answerObj[key].answer) {
                                    let answer = answerObj[key].answer ? parseInt(answerObj[key].answer) : 0;
                                    answerObj[key].answer = answer;
                                    c.answer = MyCommentContent.value?.assessUser ? answerObj[key] : { answer: 0 };
                                    c.questionIndex = key;
                                }
                            }
                        }
                        return c;
                    });    
                    return r;
                });
            }
            if(question.questionType === 8) {
                (question.userAnswerList || []).forEach(item => {
                    content.value = item.answer || 0
                });
                let col = question.content && question.content.col || [];
                let row = question.content && question.content.row || [];
                let temp = col[0].attr && col[0].attr.checkValue || {};
                minLength.value = temp.min || 0;
                maxLength.value = temp.max || 0;
            }
        })
        initInfo = deepCopy(MyCommentContent.value)
    })
}
// 获取课程详情
async function getCourseDetail() {
    try {
        let res = await G_transmit('moocDetail', {
            queries: {
                id: route.params.moocId
            },
            silence: true
        })

        detailData.value = res.data || {};

        // 不是购买者 并且不是创建人
        let notCourseUser = !detailData.value?.isBuy && !detailData.value?.isMyCreate;

        let isPublish = detailData.value?.publishState == 1 && detailData.value?.state == 4;

        // 课程未发布 除创建人和已经报名的人都不能看
        if (!isPublish && notCourseUser) {
            handleErrorPage('unpublished', route.params.moocId);
        }
        // 慕课发布了 除创建人和已经报名的人都不能看
        if(notCourseUser) {
            handleErrorPage('notsignup', route.params.moocId);
        }
        getCommentTemplate();
    } catch(_err) {
        // 禁用课程 30800500 删除课程 30800404
        if (_err.status && _err.status.code && [30800500, 30800404].includes(_err.status.code)) {
            handleErrorPage('delete', route.params.moocId);
        }  else {
            G_dispatchEvent('toast', { message: _err?.status?.desc || '服务开小差了～', type: 'error'});
        }
    }
}

const changeContent = (value) => {
    nextTick(() => {
        setTimeout(() => {
            console.log('height', document.documentElement.offsetHeight)
            // window.scrollTo(0, document.documentElement.offsetHeight)
            window.scrollTo({
                top: document.documentElement.offsetHeight,
                behavior: 'smooth'
            })
        }, 13)
    })

}

// 发表评价
function checkValidAssess () {
    console.log('MyCommentContent', MyCommentContent.value)
    let startValid = true
    let commentValid = true;
    answerArrToValid.value = [];
    MyCommentContent.value.questionList.forEach((question)=> {
        let tempObj = {
            questionType: question.questionType,
            questionId: question.id,
            isEdited: 2,
            indexList: []
        }
        if(question.questionType === 7) {
            let col = question.content && question.content.col || [];
            let row = question.content && question.content.row || [];
            row.forEach(item => {
                if(!item.col[0].answer.answer) {
                    startValid = false
                } else {
                    item.col[0].itemList.forEach(c => {
                        if(parseInt(c.title) === parseInt(item.col[0].answer.answer)) {
                            let tempIndex = `${item.index}-${item.col[0].index}-${c.index}`;
                            tempObj.indexList.push({
                                questionIndex: tempIndex,
                                answer: parseInt(item.col[0].answer.answer)
                            })
                            console.log('tempIndex', tempIndex)
                        }
                    })
                }
                
            })
        }
        if(question.questionType === 8) {
            if (!content.value || (content.value && !content.value.trim()) || (content.value && content.value.trim().length < 2)) {
                commentValid = false;
            } else {
                let col = question.content && question.content.col || [];
                let tempIndex = col[0].index;
                tempObj.indexList.push({
                    questionIndex: tempIndex,
                    answer: content.value
                })
            }
        }
        answerArrToValid.value.push(tempObj)
    })
    console.log('answerArrToValid', answerArrToValid.value)
    if (!startValid) {
        G_dispatchEvent('toast', { message: '请完成全部项打分', type: 'error'});
        return;
    }
    if (!commentValid) {
        G_dispatchEvent('toast', { message: '请输入正确的评价内容', type: 'error'});
        return;
    }
    show.value = true
}
const submit = () => {
    isNext = false
    loading.value = true
    G_transmit('assessSaveAnswer', {
        data: {
            assessId: route.params.assessId || '',
            subBizId: route.params.moocId || '',
            subBizType: 'mooc',
            state: 2,
            items: answerArrToValid.value,
            userName: currentUser.value.name || '',
            // queryInvalid: true // 查询包括删除的
        }
    }).then((res) => {
        G_dispatchEvent('toast', { message: '评分成功', type: 'success'});
        show.value = false
        loading.value = false
        getCommentTemplate();
    }).catch(_err => {
        console.log(_err);
        loading.value = false
    })
}
const cancel = () => {
    show.value = false
}
const exit = () => {
    console.log('exit')
    isNext = false
    store.dispatch('jsBridge/disposeBridge', {
        isBack: true,
        data: {
            refresh: false
        }
    });
}
const cancelExit = () => {
    showExit.value = false
}
onBeforeRouteLeave((to, from, next) => {
    console.log('to', !MyCommentContent.value.assessUser && (JSON.stringify(MyCommentContent.value) != JSON.stringify(initInfo)||content.value) && isNext)
    if (!MyCommentContent.value.assessUser && (JSON.stringify(MyCommentContent.value) != JSON.stringify(initInfo) || content.value) && isNext) {
        setTimeout(() => {
            showExit.value = true;
        }, 10);
        next(false);
    } else {
        next();
    }
});
onMounted(() => {
    store.dispatch('jsBridge/disposeBridge', {
        method: 'setNativeTitle',
        options: {
            title: '评分',
            showBack: true
        }
    });
    getCourseDetail();
    if(isApp()) {
        store.dispatch('jsBridge/SXYJSBridge', {
            method: 'commonRepeatJsBridge',
            fun: 'backSetting', //  上传类型 album|camera
            data: {
                custom: true
            },
            callback: (data) => {
                console.log('custom', data)
                if (!MyCommentContent.value.assessUser && (JSON.stringify(MyCommentContent.value) != JSON.stringify(initInfo) || content.value) && isNext) {
                    setTimeout(() => {
                        showExit.value = true;
                    }, 10);
                } else {
                    store.dispatch('jsBridge/disposeBridge', {
                        isBack: true,
                        data: {
                            refresh: false
                        }
                    });
                }
            }
        });
    }
});
</script>
<style lang="scss" scoped>
.rate-container {
    min-height: 100vh;
    background: #ffffff;
    padding-bottom: 60px;
    .content {
        font-family: PingFangSC-Regular, PingFang SC;
        .van-rate {
            vertical-align: top;
            margin-left: 20px;
        }
        .rate-box {
            padding: 30px 18px;
            .rate-item {
                display: inline-flex;
                margin-top: 25px;
                .rate-label {
                    width: 96px;
                    text-align: right;
                    font-size: 14px;
                    font-weight: 400;
                    color: #171A1D;
                    line-height: 22px;
                }
                .rate-value {
                    font-size: 14px;
                    font-weight: 400;
                    color: #6E7074;
                    line-height: 22px;
                    margin-left: 20px;
                }
            }
            .rate-item:nth-child(1) {
                margin-top: 0;
            }
        }
        .rate-desc {
            .van-cell-group {
                margin: 0;
            }
            .van-field {
                padding: 15px;
                margin: 0;
                :deep(.van-field__value){
                    textarea {
                        min-height: 190px;
                    }
                    textarea::-webkit-input-placeholder{   /* 使用webkit内核的浏览器 */
                        font-size: 14px;
                        font-weight: 400;
                        color: #A2A3A4;
                        line-height: 22px;
                    }
                    textarea:-moz-placeholder{    /* Firefox版本4-18 */
                        font-size: 14px;
                        font-weight: 400;
                        color: #A2A3A4;
                        line-height: 22px;
                    }              
                    textarea::-moz-placeholder{    /* Firefox版本19+ */
                        font-size: 14px;
                        font-weight: 400;
                        color: #A2A3A4;
                        line-height: 22px;
                    }              
                    textarea:-ms-input-placeholder{   /* IE浏览器 */
                        font-size: 14px;
                        font-weight: 400;
                        color: #A2A3A4;
                        line-height: 22px;
                    }
                }
            }
            .rate-desc-readonly {
                padding: 15px;
                font-size: 14px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #171A1D;
                line-height: 22px;
                word-break: break-word;
            }
        }
        .rate-content {
            border-top: 10px solid #F5F5F5;
            &:nth-child(1) {
                border-top: none;
            }
        }
    }
    footer {
        width: 100%;
        position: fixed;
        left: 0;
        bottom: 0;
        background: #ffffff;
        padding: 8px 15px;
        padding-bottom: calc(constant(safe-area-inset-bottom) + 15px);
        padding-bottom: calc(env(safe-area-inset-bottom) + 15px);
        box-shadow: 0px -4px 6px 0px rgba(140,149,179,0.08);
        .van-button {
            width: 100%;
            height: 44px;
            border-radius: 4px;
            background-color: #0084F6;
            font-size: 16px;
        }
    }
}
:deep(.van-popup--bottom.van-popup--round) {
    border-radius: 8px 8px 0px 0px;
}
.confirm-header {
    padding: 13px 0 12px;
    border-bottom: 1px solid #EEEEEE;
    text-align: center;
    .confirm-title {
        font-size: 16px;
        font-family: PingFangSC-Semibold, PingFang SC;
        font-weight: 600;
        color: #171A1D;
        line-height: 24px;
    }
    .confirm-desc {
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #6E7074;
        margin-top: 6px;
    }
}
.confirm-ok {
    padding: 12px 0;
    font-size: 16px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #171A1D;
    line-height: 24px;
    text-align: center;
}
.confirm-cancel {
    padding: 12px 0;
    font-size: 16px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #171A1D;
    line-height: 24px;
    text-align: center;
    border-top: 8px solid #F5F5F5;
}
</style>
